//
//  ShowOrderDetailViewController.m
//  YunGou
//
//  Created by macbook on 16/5/23.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "ShowOrderDetailViewController.h"
#import "GoodsDetailViewController.h"
#import "OrderDetailPhotoView.h"
#import "NSString+DateTransform.h"
#import "NSString+Frame.h"
#import "ProductModel.h"
#import <Masonry.h>
#import <UIImageView+WebCache.h>
#import "ShowOrderDetailCell.h"
#import "ShowOrderCommentCell.h"
#import "ShowOrderWinInfoCell.h"

@interface ShowOrderDetailViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (weak, nonatomic) IBOutlet UITextField *commentText;

@property (weak, nonatomic) IBOutlet UIButton *sendBtn;
@property (nonatomic,strong) ProductModel *productModel;
@property (nonatomic,strong) NSMutableArray *commentArray;
@end

@implementation ShowOrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _sendBtn.enabled = NO;
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //添加键盘监听事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealKeyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealKeyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleKeyBoard)];
    [self.view addGestureRecognizer:tap];
    
    _productModel = [ProductModel new];
    _productModel.Id = _showOrderModel.Id;
    _productModel.username = _showOrderModel.username;
    _productModel.img = _showOrderModel.img;
    _productModel.q_end_time = [_showOrderModel.q_end_time doubleValue];
    _productModel.title = _showOrderModel.title;
    _productModel.qishu = _showOrderModel.qishu;
    _productModel.money = _showOrderModel.money;
    _productModel.canyurenshu = _showOrderModel.canyurenshu;
    _productModel.zongrenshu = _showOrderModel.zongrenshu;
    _productModel.picarr = _showOrderModel.picarr;
    _productModel.content = _showOrderModel.content;
    
    [_commentText addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
    
    [self loadComment];
}

//监听评论框评论内容变化
- (void)valueChanged:(UITextField *)field{
    if (field.text.length > 0) {
        _sendBtn.enabled = YES;
        [_sendBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }else{
        _sendBtn.enabled = NO;
        [_sendBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
}

- (void)handleKeyBoard{
    [_commentText resignFirstResponder];
}

//加载评论
- (void)loadComment{
    [NetWorkTool commentListWithSdId:_showOrderModel.sd_id success:^(id object) {
        _commentArray = [NSMutableArray array];
        if ([object[@"code"] integerValue] == 1) {
            for (NSDictionary *dict in object[@"data"]) {
                ShowOrderCommentModel *model = [ShowOrderCommentModel modelWithDict:dict];
                [_commentArray addObject:model];
            }
        }
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
    } failure:^(NSError *error) {
        
    }];
}

#pragma -mark 键盘监听事件
-(void)dealKeyboardShow:(NSNotification *)notifi
{
    double duration = [notifi.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    NSValue *value = notifi.userInfo[UIKeyboardFrameEndUserInfoKey];
    CGRect frame;
    [value getValue:&frame];
    
    [UIView animateWithDuration:duration animations:^{
        _bottomConstraint.constant = frame.size.height;
    }];
}

-(void)dealKeyboardHide:(NSNotification *)n
{
    double duration = [n.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        _bottomConstraint.constant = 0;
    }];
}


//发送评论
- (IBAction)sendCommentClicked:(id)sender {
    if (!IsLogin) {
        [MBProgressHUD showError:@"您还未登录"];
    }
    
    if (_commentText.text.length == 0) {
        [MBProgressHUD showError:@"内容不能为空"];
        return;
    }
    [NetWorkTool addCommentWithSdId:_showOrderModel.sd_id username:[UserModel sharedInstance].username content:_commentText.text success:^(id object) {
        if ([object[@"code"] integerValue] == 1) {
            [MBProgressHUD showSuccess:@"评论成功"];
            [_commentText resignFirstResponder];
            _commentText.text = @"";
            _sendBtn.enabled = NO;
            [self loadComment];
        }else{
            [MBProgressHUD showError:@"添加失败"];
        }
    } failure:^(NSError *error) {
        FZLog(@"-------");
    }];
}

#pragma -mark tableViewDelegate and DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 2;
    }return _commentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *baseCell = nil;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            ShowOrderWinInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
            cell.orderModel = _showOrderModel;
            cell.block = ^{
                GoodsDetailViewController *goodsDetailVC = SB(@"Common", @"GoodsDetailVC");
                goodsDetailVC.productModel = _productModel;
                [self.navigationController pushViewController:goodsDetailVC animated:YES];
            };
            baseCell = cell;
        }else{
            ShowOrderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
            cell.showOrderModel = _showOrderModel;
            baseCell = cell;
        }
    }else{
        ShowOrderCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        cell.model = _commentArray[indexPath.row];
        baseCell = cell;
    }
    return baseCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            CGFloat height = [[NSString stringWithFormat:@"获得奖品%@",_showOrderModel.title] heightWithFont:[UIFont systemFontOfSize:12] withinWidth:ScreenWidth-48];
            return 160 - 14.5 + height;
        }
        return 24 + [_showOrderModel.sd_content heightWithFont:[UIFont systemFontOfSize:16] withinWidth:ScreenWidth - 32] + [OrderDetailPhotoView heightOfContent:_showOrderModel.sd_photolist withInWidth:ScreenWidth - 32];
    }else{
        ShowOrderCommentModel *commentModel = _commentArray[indexPath.row];
        CGFloat height = 69 - 14.5 + [commentModel.sdhf_content heightWithFont:[UIFont systemFontOfSize:12] withinWidth:ScreenWidth - 92];
        return height > 69?height:69;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01f;
    }return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
        headerView.backgroundColor = [UIColor whiteColor];
        UILabel *titLabel = [[UILabel alloc] init];
        titLabel.text = [NSString stringWithFormat:@"共%ld条评论",_commentArray.count];
        titLabel.font = [UIFont systemFontOfSize:13];
        [headerView addSubview:titLabel];
        [titLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(headerView).offset(16);
            make.centerY.mas_equalTo(headerView);
        }];
        UIView *lineView = [UIView new];
        lineView.backgroundColor = [UIColor colorWithHexString:@"d1d1d1"];
        [headerView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(headerView);
            make.right.mas_equalTo(headerView);
            make.bottom.mas_equalTo(headerView);
            make.height.mas_equalTo(1);
        }];
        return headerView;
        
    }return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
